﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace KongMing.Project.Common
{
    public class IOTools
    {
        /// <summary>
        /// 字符串内容写入文件，并且保存
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="conents">写入的字符串内容</param>
        public static async Task WriteFileAsync(string path, string conents)
        {
            if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(conents))
                return;
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    await sw.WriteLineAsync(conents);
                }
            }
        }

        /// <summary>
        /// 获取到本地的文件并且解析返回对应的文本
        /// </summary>
        /// <param name="filepath">文件路径</param>
        public static async Task<string> GetFileAsync(string filepath)
        {
            string content = string.Empty;
            if (string.IsNullOrWhiteSpace(filepath))
                return content;
            try
            {
                using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                    {
                        content = await sr.ReadToEndAsync();
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return content;
        }

        /// <summary>
        /// 从远程地址下载文件保存到指定路径
        /// </summary>
        /// <param name="fileUrl">文件的地址</param>
        /// <param name="savePath">保存的路径</param>
        public static async Task DownLoadFile(string fileUrl, string savePath, string fileName)
        {
            if (File.Exists($"{savePath}/{fileName}"))
                return;
            using (var web = new WebClient())
            {
                try
                {
                    if (!Directory.Exists(savePath))
                        Directory.CreateDirectory(savePath);
                    await web.DownloadFileTaskAsync(fileUrl, $"{savePath}/{fileName}");
                }
                catch (Exception ex)
                {
                    if (File.Exists(savePath))
                        File.Delete(savePath);
                    throw ex;
                }
            }
        }


        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件所在目录</param>
        ///  <param name="unZipPath">解压文件所在目录</param>
        public static async Task<bool> UnZipFileAsync(string zipFilePath, string unZipPath)
        {
            try
            {
                ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath));
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(unZipPath);
                    string fileName = Path.GetFileName(theEntry.Name);

                    //生成解压目录
                    Directory.CreateDirectory(directoryName);

                    if (fileName != String.Empty)
                    {
                        //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
                        if (theEntry.CompressedSize == 0)
                            break;
                        //解压文件到指定的目录
                        directoryName = Path.GetDirectoryName(unZipPath + "/" + theEntry.Name);
                        //建立下面的目录和子目录
                        Directory.CreateDirectory(directoryName);
                        FileStream streamWriter = File.Create(unZipPath + "/" + theEntry.Name);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = await s.ReadAsync(data, 0, data.Length);
                            if (size > 0)
                            {
                                await streamWriter.WriteAsync(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
                s.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("解压文件发生异常：" + ex.ToString());
            }
        }

    }
}
